package com.hxexp.weixin.common.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 配置文件工具类
 *
 * @author li.jiang
 *
 */
public final class ConfigFileUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigFileUtils.class);
    private static final Map<String, Properties> CONFIG_FILE_MAP = Collections.synchronizedMap(new LinkedHashMap<String, Properties>(5));

    private ConfigFileUtils() {
    }

    /**
     * 获取指定配置文件的属性集合
     *
     * @param configFilePath
     *            配置文件类路径
     * @return 属性集合
     */
    public static final Properties getProperties(String configFilePath) {
        Properties p = CONFIG_FILE_MAP.get(configFilePath);
        if (p == null) {
            p = loadConfigFile(configFilePath);
            CONFIG_FILE_MAP.put(configFilePath, p);
        }

        return p;
    }

    /**
     * 读入配置文件
     *
     * @param configFilePath
     *            配置文件类路径
     * @return 属性集合
     */
    private static final Properties loadConfigFile(String configFilePath) {
        InputStream inputStream = ConfigFileUtils.class.getClassLoader().getResourceAsStream(configFilePath);
        Properties p = new Properties();
        try {
            p.load(inputStream);
        } catch (IOException e) {
            LOGGER.error("读入配置文件时发生异常！", e);
        }

        return p;
    }
}
